package com.xudow.app.dynamicstate_old.module.follow;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jakewharton.rxbinding.view.RxView;
import com.jude.beam.bijection.RequiresPresenter;
import com.jude.beam.expansion.list.BeamListActivity;
import com.jude.beam.expansion.list.ListConfig;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.jude.utils.JUtils;
import com.squareup.picasso.Picasso;
import com.umeng.share.ShareManager;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.dynamicstate_old.JTimeTransform;
import com.xudow.app.dynamicstate_old.data.DynamicModel;
import com.xudow.app.dynamicstate_old.data.ImageModel;
import com.xudow.app.dynamicstate_old.data.server.ErrorTransform;
import com.xudow.app.dynamicstate_old.domain.Config;
import com.xudow.app.dynamicstate_old.domain.entity.Dynamic;
import com.xudow.app.dynamicstate_old.domain.entity.DynamicComment;
import com.xudow.app.dynamicstate_old.domain.entity.DynamicLike;
import com.xudow.app.dynamicstate_old.module.follow.viewholder.DynamicCommentViewHolder;
import com.xudow.app.dynamicstate_old.module.follow.viewholder.DynamicFowardViewHolder;
import com.xudow.app.dynamicstate_old.module.user.UserProfileActivity;
import com.xudow.app.dynamicstate_old.widget.ArticleSpan;
import com.xudow.app.dynamicstate_old.widget.exview.ExGridView;
import com.xudow.app.dynamicstate_old.widget.exview.NetImageAdapter;
import com.xudow.app.newui.PreLoginActivity;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by ske on 2016/7/15.
 */
@RequiresPresenter(DynamicLongPresenter.class)
public class DynamicLongActivity extends BeamListActivity<DynamicLongPresenter, Object> implements View.OnClickListener, RecyclerArrayAdapter.OnItemClickListener {
    @BindView(R.id.dynamic_follows_content_thumbup)
    ImageView dynamicFollowsContentThumbup;
    @BindView(R.id.ll_thumb_up)
    LinearLayout llThumbUp;
    @BindView(R.id.ll_comment)
    View llComment;
    @BindView(R.id.ll_forward)
    View llForward;
    @BindView(R.id.image_share)
    ImageView imageShare;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        setupView();
        app = (XApplication) getApplication();
    }

    XApplication app;
    Dynamic dynamic;

    private void setupView() {
        llThumbUp.setOnClickListener(this);
        getPresenter().getAdapter().setOnItemClickListener(this);
        llComment.setOnClickListener(this);
        llForward.setOnClickListener(this);
    }

    @Override
    public int getLayout() {
        return R.layout.activity_dynamic_detail;
    }

    @Override
    public ListConfig getConfig() {
        return super.getConfig().setContainerEmptyAble(false)
                .setLoadmoreAble(false)
                .setNoMoreAble(false);
    }

    @Override
    public int getViewType(int position) {
        if (getPresenter().getAdapter().getItem(position) instanceof DynamicComment)
            return 1;
        else
            return 2;
    }

    @Override
    public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
        if (viewType == 1)
            return new DynamicCommentViewHolder(parent);
        else
            return new DynamicFowardViewHolder(parent);
    }

    public View getHeader(ViewGroup parent, Dynamic dynamic, List<DynamicLike> dynamicLikes) {
        this.dynamic = dynamic;
        View view = getLayoutInflater().inflate(R.layout.head_of_dynamic_detail_long, parent, false);
        CircleImageView avatar = (CircleImageView) view.findViewById(R.id.dynamic_follows_item_avatar);
        Picasso.with(this).load(ImageModel.getXueDouImage(dynamic.getHeadUrl()))
                .placeholder(R.drawable.default_head_img)
                .resize(300, 300).into(avatar);
        avatar.setOnClickListener(v -> {
            Intent i = new Intent(this, UserProfileActivity.class);
            i.putExtra(UserProfileActivity.USER_PROFILE_ID, dynamic.getUserProfileId());
            startActivity(i);
        });
        ((TextView) view.findViewById(R.id.dynamic_follows_content_long_title)).setText(dynamic.getTitle());
        ((TextView) view.findViewById(R.id.dynamic_follows_item_name)).setText(dynamic.getUserName());
        ((TextView) view.findViewById(R.id.dynamic_follows_item_time)).setText(new JTimeTransform(dynamic.getPublishTime()).toString(new JTimeTransform.RecentDateFormat("MM-dd hh:mm")));
        TextView longPostContent = (TextView) view.findViewById(R.id.dynamic_follows_content_long);
        String source = dynamic.getContent() + "..." + "全文详情";
        SpannableString spannableString = new SpannableString(source);
        spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.name_color)), source.length() - 4, source.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ArticleSpan(DynamicLongActivity.this) {
            @Override
            public void onClick(View widget) {
                Intent i = new Intent(DynamicLongActivity.this, DynamicLongDetailActivity.class);
                i.putExtra("dynamic", dynamic);
                startActivity(i);
            }
        }, source.length() - 4, source.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        longPostContent.setMovementMethod(LinkMovementMethod.getInstance());
        longPostContent.setText(spannableString);

        view.findViewById(R.id.dynamic_follows_content_layout_long).setOnClickListener(v -> {
            Intent i = new Intent(this, DynamicLongDetailActivity.class);
            i.putExtra("dynamic", dynamic);
            startActivity(i);
        });
        final ImageView imgCollect = (ImageView) view.findViewById(R.id.dynamic_follows_item_control);
        if (dynamic.getIsCollected() == 1) {
            imgCollect.setImageResource(R.drawable.collected_dynamic);
        } else {
            imgCollect.setImageResource(R.drawable.collect);
        }
        imgCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!app.isLogin()) {
                    startActivity(new Intent(DynamicLongActivity.this, PreLoginActivity.class));
                    return;
                }
                imgCollect.setClickable(false);
                if (dynamic.getIsCollected() == 0)
                    collect(imgCollect);
                else
                    unCollect(imgCollect);
            }
        });
        if (!TextUtils.isEmpty(dynamic.getImgpath())) {
            ExGridView pictures = (ExGridView) view.findViewById(R.id.dynamic_follows_content_long_grid);
            pictures.setColumnCount(3);
            pictures.setAdapter(new NetImageAdapter(this, dynamic.getImgpath().split(";")));
        }
        ((TextView) view.findViewById(R.id.praise_text)).setText(dynamic.getLikeNum() + "点赞");
        ((TextView) view.findViewById(R.id.text_num_comment)).setText(dynamic.getCommentNum() + "");
        ((TextView) view.findViewById(R.id.text_num_forward)).setText(dynamic.getForwardNum() + "");
        ExGridView praiseMember = (ExGridView) view.findViewById(R.id.praise_member);
        if (dynamicLikes != null) {
            for (DynamicLike like : dynamicLikes) {
                CircleImageView imageView = new CircleImageView(DynamicLongActivity.this);
                Picasso.with(DynamicLongActivity.this).load(ImageModel.getXueDouImage(like.getHeadUrl())).placeholder(R.drawable.default_head_img).into(imageView);
                praiseMember.addView(imageView);
                imageView.setOnClickListener(v -> {
                    Intent i = new Intent(this, UserProfileActivity.class);
                    i.putExtra(UserProfileActivity.USER_PROFILE_ID, like.getUserProfileId());
                    startActivity(i);
                });
            }
        }
        RxView.clicks(view.findViewById(R.id.btn_comment))
                .subscribe(v -> getPresenter().showComment());
        RxView.clicks(view.findViewById(R.id.btn_foward))
                .subscribe(v -> getPresenter().showFoward());
        setTool();
        return view;
    }

    private void setTool() {
        imageShare.setOnClickListener(v -> share());
        dynamicFollowsContentThumbup.setImageResource(dynamic.getIsLiked() == 1 ? R.drawable.dynamic_follows_like_after : R.drawable.dynamic_follows_like);
    }

    @OnClick(R.id.image_back)
    void back(View view) {
        onBackPressed();
    }

    @Override
    public void onClick(View v) {
        if (!app.isLogin()) {
            startActivity(new Intent(this, PreLoginActivity.class));
            return;
        }
        switch (v.getId()) {
            case R.id.ll_thumb_up:
                if (dynamic.getIsLiked() == 0) {
                    thumbUp();
                } else {
                    unThumbUp();
                }
                break;
            case R.id.ll_comment:
                Intent intent = new Intent(DynamicLongActivity.this, CommentActivity.class);
                intent.putExtra("dynamic", dynamic);
                startActivityForResult(intent, 10001);
                break;
            case R.id.ll_forward:
                Intent forwardIntent = new Intent(DynamicLongActivity.this, ForwardActivity.class);
                forwardIntent.putExtra("dynamic", dynamic);
                forwardIntent.putExtra("type", 1);
                startActivity(forwardIntent);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra("dynamic", dynamic);
        setResult(RESULT_OK, intent);
        super.onBackPressed();
    }

    @Override
    public void onItemClick(final int position) {
        DynamicComment dynamicComment = getPresenter().mCommentList.get(position);
//        自己
        if (dynamicComment.getUserProfileId() == app.getUserProfileId()) {
            Dialog mBottomSheetDialog = new Dialog(this, R.style.MaterialDialogSheet);
            View view = getLayoutInflater().inflate(R.layout.dialog_comment_self, null);
            mBottomSheetDialog.setContentView(view);
            view.findViewById(R.id.text_delete).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    delCommentSelf(dynamicComment, position);
                    mBottomSheetDialog.dismiss();
                }
            });
            mBottomSheetDialog.setCancelable(true);
            mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
            mBottomSheetDialog.show();
        } else {
            reply(position);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ShareManager.getInstance(this).onActivityResult(this, requestCode, resultCode, data);
        if (requestCode == 10001 && resultCode == RESULT_OK) {
            getPresenter().onRefresh();
        }
    }

    private void delCommentSelf(DynamicComment comment, int position) {
        DynamicModel.getInstance().deleteComment(dynamic.getId(), comment.getId())
                .compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST))
                .subscribe(message -> {
                    JUtils.Toast("删除成功");
                    getPresenter().onRefresh();
                });
    }

    private void reply(int position) {
        Intent intent = new Intent(DynamicLongActivity.this, CommentActivity.class);
        intent.putExtra("dynamic", dynamic);
        intent.putExtra("dynamicComment", getPresenter().mCommentList.get(position));
        startActivityForResult(intent, 10001);
    }

    private void collect(final ImageView imgCollect) {
        DynamicModel.getInstance().collectDynamic(dynamic.getId())
                .doAfterTerminate(() -> imgCollect.setClickable(true))
                .compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST))
                .subscribe(message -> {
                    JUtils.Toast("收藏成功");
                    dynamic.setIsCollected(1);
                    imgCollect.setImageResource(R.drawable.collected_dynamic);
                });
    }

    private void unCollect(final ImageView imgCollect) {
        DynamicModel.getInstance().unCollectDynamic(dynamic.getId())
                .doAfterTerminate(() -> imgCollect.setClickable(true))
                .compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST))
                .subscribe(message -> {
                    JUtils.Toast("取消收藏成功");
                    dynamic.setIsCollected(0);
                    imgCollect.setImageResource(R.drawable.collect);
                });
    }

    private void thumbUp() {
        DynamicModel.getInstance().like(dynamic.getId(), app.isStudent() ? 2 : 1)
                .compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST))
                .subscribe(message -> {
                    dynamic.setIsLiked(1);
                    dynamic.setLikeNum(dynamic.getLikeNum() + 1);
                    getPresenter().onRefresh();
                });
    }

    private void unThumbUp() {
        DynamicModel.getInstance().unLike(dynamic.getId())
                .compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST))
                .subscribe(message -> {
                    dynamic.setIsLiked(0);
                    dynamic.setLikeNum(dynamic.getLikeNum() - 1);
                    getPresenter().onRefresh();
                });
    }

    public void share() {
        String content = dynamic.getContent();
        ShareManager.getInstance(this).shareContent(this, content, "http://url.cn/2EAOTU5", "学兜分享", dynamic.getImgpath()
                , new UMShareListener() {
                    @Override
                    public void onResult(SHARE_MEDIA platform) {
                        Toast.makeText(DynamicLongActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(SHARE_MEDIA platform, Throwable t) {
                        JUtils.Log(t.getMessage());
                        Toast.makeText(DynamicLongActivity.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA platform) {
                        Toast.makeText(DynamicLongActivity.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
                    }
                });
    }
}
